# uncompyle6 version 3.2.3
# Python bytecode 3.6 (3379)
# Decompiled from: Python 3.6.8 |Anaconda custom (64-bit)| (default, Feb 21 2019, 18:30:04) [MSC v.1916 64 bit (AMD64)]
# Embedded file name: site-packages\gevent\builtins.py
"""gevent friendly implementations of builtin functions."""
from __future__ import absolute_import
import imp, sys, weakref
from gevent.lock import RLock

try:
    import __builtin__ as builtins

    _allowed_module_name_types = (basestring,)
    __target__ = "__builtin__"
except ImportError:
    import builtins

    _allowed_module_name_types = (str,)
    __target__ = "builtins"

_import = builtins.__import__
_g_import_locks = {}
__lock_imports = True


def __module_lock(name):
    lock = None
    try:
        lock = _g_import_locks[name]()
    except KeyError:
        pass

    if lock is None:
        lock = RLock()

        def cb(_):
            _g_import_locks.pop(name, None)

        _g_import_locks[name] = weakref.ref(lock, cb)
    return lock


def __import__(*args, **kwargs):
    """
    __import__(name, globals=None, locals=None, fromlist=(), level=0) -> object
    
    Normally python protects imports against concurrency by doing some locking
    at the C level (at least, it does that in CPython).  This function just
    wraps the normal __import__ functionality in a recursive lock, ensuring that
    we're protected against greenlet import concurrency as well.
    """
    global __lock_imports
    if args:
        if not issubclass(type(args[0]), _allowed_module_name_types):
            args = args[1:]
    if not __lock_imports:
        return _import(*args, **kwargs)
    else:
        module_lock = __module_lock(args[0])
        imp.acquire_lock()
        try:
            module_lock.acquire()
            try:
                result = _import(*args, **kwargs)
            finally:
                module_lock.release()

        finally:
            imp.release_lock()

        return result


def _unlock_imports():
    """
    Internal function, called when gevent needs to perform imports
    lazily, but does not know the state of the system. It may be impossible
    to take the import lock because there are no other running greenlets, for
    example. This causes a monkey-patched __import__ to avoid taking any locks.
    until the corresponding call to lock_imports. This should only be done for limited
    amounts of time and when the set of imports is statically known to be "safe".
    """
    global __lock_imports
    __lock_imports = False


def _lock_imports():
    global __lock_imports
    __lock_imports = True


if sys.version_info[:2] >= (3, 3):
    __implements__ = []
else:
    __implements__ = ["__import__"]
__all__ = __implements__
